home *** CD-ROM | disk | FTP | other *** search
/ MacAddict 104 / MacAddict_104_2005-04.iso / Software / Internet & Communication / WordPress 1.2.2 freeware.dmg / wordpress / wp-includes / functions.php < prev    next >
Encoding:
PHP Script  |  2004-12-16  |  47.7 KB  |  1,428 lines

  1. <?php
  2.  
  3. if (!function_exists('_')) {
  4.     function _($string) {
  5.         return $string;
  6.     }
  7. }
  8.  
  9. if (!function_exists('floatval')) {
  10.     function floatval($string) {
  11.         return ((float) $string);
  12.     }
  13. }
  14.  
  15. function popuplinks($text) {
  16.     // Comment text in popup windows should be filtered through this.
  17.     // Right now it's a moderately dumb function, ideally it would detect whether
  18.     // a target or rel attribute was already there and adjust its actions accordingly.
  19.     $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
  20.     return $text;
  21. }
  22.  
  23. // patch by Adriaan Tijsseling (http://kung-foo.tv): added an option to return the UTC string
  24. function mysql2date($dateformatstring, $mysqlstring, $use_b2configmonthsdays = 1, $utc=0) {
  25.     global $month, $weekday;
  26.     $m = $mysqlstring;
  27.     if (empty($m)) {
  28.         return false;
  29.     }
  30.     $i = mktime(substr($m,11,2),substr($m,14,2),substr($m,17,2),substr($m,5,2),substr($m,8,2),substr($m,0,4)); 
  31.     if ( $utc )
  32.     {
  33.         $i -= get_settings('gmt_offset') * 3600;
  34.     }
  35.     if (!empty($month) && !empty($weekday) && $use_b2configmonthsdays) {
  36.         $datemonth = $month[date('m', $i)];
  37.         $dateweekday = $weekday[date('w', $i)];
  38.         $dateformatstring = ' '.$dateformatstring;
  39.         $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit(substr($dateweekday, 0, 3)), $dateformatstring);
  40.         $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
  41.         $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
  42.         $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit(substr($datemonth, 0, 3)), $dateformatstring);
  43.         $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
  44.     }
  45.     $j = @date($dateformatstring, $i);
  46.     if (!$j) {
  47.     // for debug purposes
  48.     //    echo $i." ".$mysqlstring;
  49.     }
  50.     if ( $utc )
  51.        return $j . 'Z';
  52.     return $j;
  53. }
  54.  
  55. function current_time($type, $gmt = 0) {
  56.     switch ($type) {
  57.         case 'mysql':
  58.             if ($gmt) $d = gmdate('Y-m-d H:i:s');
  59.             else $d = gmdate('Y-m-d H:i:s', (time() + (get_settings('gmt_offset') * 3600)));
  60.             return $d;
  61.             break;
  62.         case 'timestamp':
  63.             if ($gmt) $d = time();
  64.             else $d = time() + (get_settings('gmt_offset') * 3600);
  65.             return $d;
  66.             break;
  67.     }
  68. }
  69.  
  70. function date_i18n($dateformatstring, $unixtimestamp) {
  71.     global $month, $weekday;
  72.     $i = $unixtimestamp; 
  73.     if ((!empty($month)) && (!empty($weekday))) {
  74.         $datemonth = $month[date('m', $i)];
  75.         $dateweekday = $weekday[date('w', $i)];
  76.         $dateformatstring = ' '.$dateformatstring;
  77.         $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit(substr($dateweekday, 0, 3)), $dateformatstring);
  78.         $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring);
  79.         $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring);
  80.         $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit(substr($datemonth, 0, 3)), $dateformatstring);
  81.         $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1);
  82.     }
  83.     $j = @date($dateformatstring, $i);
  84.     return $j;
  85.     }
  86.  
  87. function get_weekstartend($mysqlstring, $start_of_week) {
  88.     $my = substr($mysqlstring,0,4);
  89.     $mm = substr($mysqlstring,8,2);
  90.     $md = substr($mysqlstring,5,2);
  91.     $day = mktime(0,0,0, $md, $mm, $my);
  92.     $weekday = date('w',$day);
  93.     $i = 86400;
  94.     while ($weekday > get_settings('start_of_week')) {
  95.         $weekday = date('w',$day);
  96.         $day = $day - 86400;
  97.         $i = 0;
  98.     }
  99.     $week['start'] = $day + 86400 - $i;
  100.     $week['end']   = $day + 691199;
  101.     return $week;
  102. }
  103.  
  104. function get_lastpostdate($timezone = 'server') {
  105.     global $tableposts, $cache_lastpostdate, $pagenow, $wpdb;
  106.     $add_seconds_blog = get_settings('gmt_offset') * 3600;
  107.     $add_seconds_server = date('Z');
  108.     $now = current_time('mysql', 1);
  109.     if ( !isset($cache_lastpostdate[$timezone]) ) {
  110.         switch(strtolower($timezone)) {
  111.             case 'gmt':
  112.                 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $tableposts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
  113.                 break;
  114.             case 'blog':
  115.                 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $tableposts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
  116.                 break;
  117.             case 'server':
  118.                 $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $tableposts WHERE post_date_gmt <= '$now' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
  119.                 break;
  120.         }
  121.         $cache_lastpostdate[$timezone] = $lastpostdate;
  122.     } else {
  123.         $lastpostdate = $cache_lastpostdate[$timezone];
  124.     }
  125.     return $lastpostdate;
  126. }
  127.  
  128. function get_lastpostmodified($timezone = 'server') {
  129.     global $tableposts, $cache_lastpostmodified, $pagenow, $wpdb;
  130.     $add_seconds_blog = get_settings('gmt_offset') * 3600;
  131.     $add_seconds_server = date('Z');
  132.     $now = current_time('mysql', 1);
  133.     if ( !isset($cache_lastpostmodified[$timezone]) ) {
  134.         switch(strtolower($timezone)) {
  135.             case 'gmt':
  136.                 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $tableposts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
  137.                 break;
  138.             case 'blog':
  139.                 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $tableposts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
  140.                 break;
  141.             case 'server':
  142.                 $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $tableposts WHERE post_modified_gmt <= '$now' AND post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
  143.                 break;
  144.         }
  145.         $lastpostdate = get_lastpostdate($timezone);
  146.         if ($lastpostdate > $lastpostmodified) {
  147.             $lastpostmodified = $lastpostdate;
  148.         }
  149.         $cache_lastpostmodified[$timezone] = $lastpostmodified;
  150.     } else {
  151.         $lastpostmodified = $cache_lastpostmodified[$timezone];
  152.     }
  153.     return $lastpostmodified;
  154. }
  155.  
  156. function user_pass_ok($user_login,$user_pass) {
  157.     global $cache_userdata;
  158.     if ( empty($cache_userdata[$user_login]) ) {
  159.         $userdata = get_userdatabylogin($user_login);
  160.     } else {
  161.         $userdata = $cache_userdata[$user_login];
  162.     }
  163.     return (md5($user_pass) == $userdata->user_pass);
  164. }
  165.  
  166. function get_currentuserinfo() { // a bit like get_userdata(), on steroids
  167.     global $user_login, $userdata, $user_level, $user_ID, $user_nickname, $user_email, $user_url, $user_pass_md5, $cookiehash;
  168.     // *** retrieving user's data from cookies and db - no spoofing
  169.  
  170.     if (isset($_COOKIE['wordpressuser_' . $cookiehash])) 
  171.         $user_login = $_COOKIE['wordpressuser_' . $cookiehash];
  172.     $userdata = get_userdatabylogin($user_login);
  173.     $user_level = $userdata->user_level;
  174.     $user_ID = $userdata->ID;
  175.     $user_nickname = $userdata->user_nickname;
  176.     $user_email = $userdata->user_email;
  177.     $user_url = $userdata->user_url;
  178.     $user_pass_md5 = md5($userdata->user_pass);
  179. }
  180.  
  181. function get_userdata($userid) {
  182.     global $wpdb, $cache_userdata, $tableusers;
  183.     if ( empty($cache_userdata[$userid]) ) {
  184.         $user = $wpdb->get_row("SELECT * FROM $tableusers WHERE ID = '$userid'");
  185.         $user->user_nickname = stripslashes($user->user_nickname);
  186.         $user->user_firstname = stripslashes($user->user_firstname);
  187.         $user->user_lastname = stripslashes($user->user_lastname);
  188.         $user->user_description = stripslashes($user->user_description);
  189.         $cache_userdata[$userid] = $user;
  190.     } else {
  191.         $user = $cache_userdata[$userid];
  192.     }
  193.     return $user;
  194. }
  195.  
  196. function get_userdatabylogin($user_login) {
  197.     global $tableusers, $cache_userdata, $wpdb;
  198.     if ( empty($cache_userdata["$user_login"]) ) {
  199.         $user = $wpdb->get_row("SELECT * FROM $tableusers WHERE user_login = '$user_login'");
  200.         $cache_userdata["$user_login"] = $user;
  201.     } else {
  202.         $user = $cache_userdata["$user_login"];
  203.     }
  204.     return $user;
  205. }
  206.  
  207. function get_userid($user_login) {
  208.     global $tableusers, $cache_userdata, $wpdb;
  209.     if ( empty($cache_userdata["$user_login"]) ) {
  210.         $user_id = $wpdb->get_var("SELECT ID FROM $tableusers WHERE user_login = '$user_login'");
  211.  
  212.         $cache_userdata["$user_login"] = $user_id;
  213.     } else {
  214.         $user_id = $cache_userdata["$user_login"];
  215.     }
  216.     return $user_id;
  217. }
  218.  
  219. function get_usernumposts($userid) {
  220.     global $tableposts, $tablecomments, $wpdb;
  221.     return $wpdb->get_var("SELECT COUNT(*) FROM $tableposts WHERE post_author = '$userid'");
  222. }
  223.  
  224. // examine a url (supposedly from this blog) and try to
  225. // determine the post ID it represents.
  226. function url_to_postid($url = '') {
  227.     global $wpdb, $tableposts;
  228.  
  229.     $siteurl = get_settings('home');
  230.     // Take a link like 'http://example.com/blog/something'
  231.     // and extract just the '/something':
  232.     $uri = preg_replace("#$siteurl#i", '', $url);
  233.  
  234.     // on failure, preg_replace just returns the subject string
  235.     // so if $uri and $siteurl are the same, they didn't match:
  236.     if ($uri == $siteurl) 
  237.         return 0;
  238.         
  239.     // First, check to see if there is a 'p=N' to match against:
  240.     preg_match('#[?&]p=(\d+)#', $uri, $values);
  241.     $p = intval($values[1]);
  242.     if ($p) return $p;
  243.     
  244.     // Match $uri against our permalink structure
  245.     $permalink_structure = get_settings('permalink_structure');
  246.     
  247.     // Matt's tokenizer code
  248.     $rewritecode = array(
  249.         '%year%',
  250.         '%monthnum%',
  251.         '%day%',
  252.         '%hour%',
  253.         '%minute%',
  254.         '%second%',
  255.         '%postname%',
  256.         '%post_id%'
  257.     );
  258.     $rewritereplace = array(
  259.         '([0-9]{4})?',
  260.         '([0-9]{1,2})?',
  261.         '([0-9]{1,2})?',
  262.         '([0-9]{1,2})?',
  263.         '([0-9]{1,2})?',
  264.         '([0-9]{1,2})?',
  265.         '([_0-9a-z-]+)?',
  266.         '([0-9]+)?'
  267.     );
  268.  
  269.     // Turn the structure into a regular expression
  270.     $matchre = str_replace('/', '/?', $permalink_structure);
  271.     $matchre = str_replace($rewritecode, $rewritereplace, $matchre);
  272.  
  273.     // Extract the key values from the uri:
  274.     preg_match("#$matchre#",$uri,$values);
  275.  
  276.     // Extract the token names from the structure:
  277.     preg_match_all("#%(.+?)%#", $permalink_structure, $tokens);
  278.  
  279.     for($i = 0; $i < count($tokens[1]); $i++) {
  280.         $name = $tokens[1][$i];
  281.         $value = $values[$i+1];
  282.  
  283.         // Create a variable named $year, $monthnum, $day, $postname, or $post_id:
  284.         $$name = $value;
  285.     }
  286.     
  287.     // If using %post_id%, we're done:
  288.     if (intval($post_id)) return intval($post_id);
  289.  
  290.     // Otherwise, build a WHERE clause, making the values safe along the way:
  291.     if ($year) $where .= " AND YEAR(post_date) = '" . intval($year) . "'";
  292.     if ($monthnum) $where .= " AND MONTH(post_date) = '" . intval($monthnum) . "'";
  293.     if ($day) $where .= " AND DAYOFMONTH(post_date) = '" . intval($day) . "'";
  294.     if ($hour) $where .= " AND HOUR(post_date) = '" . intval($hour) . "'";
  295.     if ($minute) $where .= " AND MINUTE(post_date) = '" . intval($minute) . "'";
  296.     if ($second) $where .= " AND SECOND(post_date) = '" . intval($second) . "'";
  297.     if ($postname) $where .= " AND post_name = '" . $wpdb->escape($postname) . "' ";
  298.  
  299.     // Run the query to get the post ID:
  300.     $id = intval($wpdb->get_var("SELECT ID FROM $tableposts WHERE 1 = 1 " . $where));
  301.  
  302.     return $id;
  303. }
  304.  
  305.  
  306. /* Options functions */
  307.  
  308. function get_settings($setting) {
  309.     global $wpdb, $cache_settings;
  310.     if (strstr($_SERVER['REQUEST_URI'], 'install.php')) {
  311.         return false;
  312.     }
  313.  
  314.     if ( (empty($cache_settings)) ) {
  315.         $settings = get_alloptions();
  316.         $cache_settings = $settings;
  317.     } else {
  318.         $settings = $cache_settings;
  319.     }
  320.  
  321.     if ('home' == $setting && '' == $settings->home) return $settings->siteurl;
  322.  
  323.     if (!isset($settings->$setting)) {
  324.         return false;
  325.     } else {
  326.         return stripslashes($settings->$setting);
  327.     }
  328. }
  329.  
  330. function get_alloptions() {
  331.     global $tableoptions, $wpdb;
  332.     $options = $wpdb->get_results("SELECT option_name, option_value FROM $tableoptions");
  333.     if ($options) {
  334.         foreach ($options as $option) {
  335.             // "When trying to design a foolproof system, 
  336.             //  never underestimate the ingenuity of the fools :)"
  337.             if ('siteurl' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  338.             if ('home' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  339.             if ('category_base' == $option->option_name) $option->option_value = preg_replace('|/+$|', '', $option->option_value);
  340.  
  341.             $all_options->{$option->option_name} = $option->option_value;
  342.         }
  343.     }
  344.     return $all_options;
  345. }
  346.  
  347. function update_option($option_name, $newvalue) {
  348.     global $wpdb, $tableoptions, $cache_settings;
  349.     $newvalue = stripslashes($newvalue);
  350.     $newvalue = trim($newvalue); // I can't think of any situation we wouldn't want to trim
  351.     $newvalue = $wpdb->escape($newvalue);
  352.     $wpdb->query("UPDATE $tableoptions SET option_value = '$newvalue' WHERE option_name = '$option_name'");
  353.     $cache_settings = get_alloptions(); // Re cache settings
  354.     return true;
  355. }
  356.  
  357.  
  358. // thx Alex Stapleton, http://alex.vort-x.net/blog/
  359. function add_option($name, $value='') {
  360.     // Adds an option if it doesn't already exist
  361.     global $wpdb, $tableoptions;
  362.     if(!get_settings($name)) {
  363.         $name = $wpdb->escape($name);
  364.         $value = $wpdb->escape($value);
  365.         $wpdb->query("INSERT INTO $tableoptions (option_name, option_value) VALUES ('$name', '$value')");
  366.  
  367.         if($wpdb->insert_id) {
  368.             global $cache_settings;
  369.             $cache_settings->{$name} = $value;
  370.         }
  371.     }
  372.     return;
  373. }
  374.  
  375. function delete_option($name) {
  376.     global $wpdb, $tableoptions, $tableoptiongroup_options;
  377.     // Get the ID, if no ID then return
  378.     $option_id = $wpdb->get_var("SELECT option_id FROM $tableoptions WHERE option_name = '$name'");
  379.     if (!$option_id) return false;
  380.     $wpdb->query("DELETE FROM $tableoptiongroup_options WHERE option_id = '$option_id'");
  381.     $wpdb->query("DELETE FROM $tableoptions WHERE option_name = '$name'");
  382.     return true;
  383. }
  384.  
  385. function get_postdata($postid) {
  386.     global $post, $tableposts, $wpdb;
  387.  
  388.     $post = $wpdb->get_row("SELECT * FROM $tableposts WHERE ID = '$postid'");
  389.     
  390.     $postdata = array (
  391.         'ID' => $post->ID, 
  392.         'Author_ID' => $post->post_author, 
  393.         'Date' => $post->post_date, 
  394.         'Content' => $post->post_content, 
  395.         'Excerpt' => $post->post_excerpt, 
  396.         'Title' => $post->post_title, 
  397.         'Category' => $post->post_category,
  398.         'Lat' => $post->post_lat,
  399.         'Lon' => $post->post_lon,
  400.         'post_status' => $post->post_status,
  401.         'comment_status' => $post->comment_status,
  402.         'ping_status' => $post->ping_status,
  403.         'post_password' => $post->post_password,
  404.         'to_ping' => $post->to_ping,
  405.         'pinged' => $post->pinged,
  406.         'post_name' => $post->post_name
  407.     );
  408.     return $postdata;
  409. }
  410.  
  411. function get_commentdata($comment_ID,$no_cache=0,$include_unapproved=false) { // less flexible, but saves DB queries
  412.     global $postc,$id,$commentdata,$tablecomments, $wpdb;
  413.     if ($no_cache) {
  414.         $query = "SELECT * FROM $tablecomments WHERE comment_ID = '$comment_ID'";
  415.         if (false == $include_unapproved) {
  416.             $query .= " AND comment_approved = '1'";
  417.         }
  418.             $myrow = $wpdb->get_row($query, ARRAY_A);
  419.     } else {
  420.         $myrow['comment_ID']=$postc->comment_ID;
  421.         $myrow['comment_post_ID']=$postc->comment_post_ID;
  422.         $myrow['comment_author']=$postc->comment_author;
  423.         $myrow['comment_author_email']=$postc->comment_author_email;
  424.         $myrow['comment_author_url']=$postc->comment_author_url;
  425.         $myrow['comment_author_IP']=$postc->comment_author_IP;
  426.         $myrow['comment_date']=$postc->comment_date;
  427.         $myrow['comment_content']=$postc->comment_content;
  428.         $myrow['comment_karma']=$postc->comment_karma;
  429.         if (strstr($myrow['comment_content'], '<trackback />')) {
  430.             $myrow['comment_type'] = 'trackback';
  431.         } elseif (strstr($myrow['comment_content'], '<pingback />')) {
  432.             $myrow['comment_type'] = 'pingback';
  433.         } else {
  434.             $myrow['comment_type'] = 'comment';
  435.         }
  436.     }
  437.     return $myrow;
  438. }
  439.  
  440. function get_catname($cat_ID) {
  441.     global $tablecategories, $cache_catnames, $wpdb;
  442.     if ( !$cache_catnames ) {
  443.         $results = $wpdb->get_results("SELECT * FROM $tablecategories") or die('Oops, couldn\'t query the db for categories.');
  444.         foreach ($results as $post) {
  445.             $cache_catnames[$post->cat_ID] = $post->cat_name;
  446.         }
  447.     }
  448.     $cat_name = $cache_catnames[$cat_ID];
  449.     return $cat_name;
  450. }
  451.  
  452. function gzip_compression() {
  453.     global $gzip_compressed;
  454.     if (strstr($_SERVER['PHP_SELF'], 'wp-admin')) return true;
  455.         if (!$gzip_compressed) {
  456.         $phpver = phpversion(); //start gzip compression
  457.         if($phpver >= "4.0.4pl1") {
  458.             if(extension_loaded("zlib")) { 
  459.                 ob_start("ob_gzhandler"); 
  460.             }
  461.         } else if($phpver > "4.0") {
  462.             if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
  463.                 if(extension_loaded("zlib")) { 
  464.                     $do_gzip_compress = TRUE; 
  465.                     ob_start(); 
  466.                     ob_implicit_flush(0); 
  467.                     header("Content-Encoding: gzip");
  468.                 }
  469.             }
  470.         } //end gzip compression - that piece of script courtesy of the phpBB dev team
  471.         $gzip_compressed=1;
  472.     }
  473. }
  474.  
  475.  
  476. // functions to count the page generation time (from phpBB2)
  477. // ( or just any time between timer_start() and timer_stop() )
  478.  
  479. function timer_start() {
  480.     global $timestart;
  481.     $mtime = microtime();
  482.     $mtime = explode(" ",$mtime);
  483.     $mtime = $mtime[1] + $mtime[0];
  484.     $timestart = $mtime;
  485.     return true;
  486. }
  487.  
  488. function timer_stop($display=0,$precision=3) { //if called like timer_stop(1), will echo $timetotal
  489.     global $timestart,$timeend;
  490.     $mtime = microtime();
  491.     $mtime = explode(" ",$mtime);
  492.     $mtime = $mtime[1] + $mtime[0];
  493.     $timeend = $mtime;
  494.     $timetotal = $timeend-$timestart;
  495.     if ($display)
  496.         echo number_format($timetotal,$precision);
  497.     return $timetotal;
  498. }
  499.  
  500. function weblog_ping($server = '', $path = '') {
  501.     $debug = false;
  502.     include_once (ABSPATH . WPINC . '/class-xmlrpc.php');
  503.     include_once (ABSPATH . WPINC . '/class-xmlrpcs.php');
  504.  
  505.     $f = new xmlrpcmsg('weblogUpdates.ping',
  506.         array(new xmlrpcval(get_settings('blogname'), 'string'),
  507.             new xmlrpcval(get_settings('home') ,'string')));
  508.     $c = new xmlrpc_client($path, $server, 80);
  509.     $r = $c->send($f);
  510.  
  511.     if ('0' != $r) {    
  512.         if ($debug) {
  513.             echo "<h3>Response Object Dump:</h3>
  514.                 <pre>\n";
  515.             print_r($r);
  516.             echo "</pre>\n";
  517.         }
  518.  
  519.         $v = @phpxmlrpc_decode($r->value());
  520.         if (!$r->faultCode()) {
  521.             $result['message'] =  "<p class=\"rpcmsg\">";
  522.             $result['message'] = $result['message'] .  $v["message"] . "<br />\n";
  523.             $result['message'] = $result['message'] . "</p>";
  524.         } else {
  525.             $result['err'] = $r->faultCode();
  526.             $result['message'] =  "<!--\n";
  527.             $result['message'] = $result['message'] . "Fault: ";
  528.             $result['message'] = $result['message'] . "Code: " . $r->faultCode();
  529.             $result['message'] = $result['message'] . " Reason '" .$r->faultString()."'<BR>";
  530.             $result['message'] = $result['message'] . "-->\n";
  531.         }
  532.  
  533.         if ($debug) print '<blockquote>' . $result['message'] . '</blockquote>';
  534.     }
  535. }
  536.  
  537. function generic_ping($post_id = 0) {
  538.     $services = get_settings('ping_sites');
  539.     $services = preg_replace("|(\s)+|", '$1', $services); // Kill dupe lines
  540.     $services = trim($services);
  541.     if ('' != $services) {
  542.         $services = explode("\n", $services);
  543.         foreach ($services as $service) {
  544.             $uri = parse_url($service);
  545.             weblog_ping($uri['host'], $uri['path']);
  546.         }
  547.     }
  548. }
  549.  
  550. add_action('publish_post', 'generic_ping');
  551.  
  552. // Send a Trackback
  553. function trackback($trackback_url, $title, $excerpt, $ID) {
  554.     global $wpdb, $tableposts;
  555.     $title = urlencode(stripslashes($title));
  556.     $excerpt = urlencode(stripslashes($excerpt));
  557.     $blog_name = urlencode(stripslashes(get_settings('blogname')));
  558.     $tb_url = $trackback_url;
  559.     $url = urlencode(get_permalink($ID));
  560.     $query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
  561.     $trackback_url = parse_url($trackback_url);
  562.     $http_request  = 'POST ' . $trackback_url['path'] . $trackback_url['query'] . " HTTP/1.0\r\n";
  563.     $http_request .= 'Host: '.$trackback_url['host']."\r\n";
  564.     $http_request .= 'Content-Type: application/x-www-form-urlencoded'."\r\n";
  565.     $http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
  566.     $http_request .= "\r\n";
  567.     $http_request .= $query_string;
  568.     $fs = @fsockopen($trackback_url['host'], 80);
  569.     @fputs($fs, $http_request);
  570. /*
  571.     $debug_file = 'trackback.log';
  572.     $fp = fopen($debug_file, 'a');
  573.     fwrite($fp, "\n*****\nRequest:\n\n$http_request\n\nResponse:\n\n");
  574.     while(!@feof($fs)) {
  575.         fwrite($fp, @fgets($fs, 4096));
  576.     }
  577.     fwrite($fp, "\n\n");
  578.     fclose($fp);
  579. */
  580.     @fclose($fs);
  581.  
  582.     $wpdb->query("UPDATE $tableposts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
  583.     $wpdb->query("UPDATE $tableposts SET to_ping = REPLACE(to_ping, '$tb_url', '') WHERE ID = '$ID'");
  584.     return $result;
  585. }
  586.  
  587. // trackback - reply
  588. function trackback_response($error = 0, $error_message = '') {
  589.     if ($error) {
  590.         echo '<?xml version="1.0" encoding="iso-8859-1"?'.">\n";
  591.         echo "<response>\n";
  592.         echo "<error>1</error>\n";
  593.         echo "<message>$error_message</message>\n";
  594.         echo "</response>";
  595.     } else {
  596.         echo '<?xml version="1.0" encoding="iso-8859-1"?'.">\n";
  597.         echo "<response>\n";
  598.         echo "<error>0</error>\n";
  599.         echo "</response>";
  600.     }
  601.     die();
  602. }
  603.  
  604. function make_url_footnote($content) {
  605.     preg_match_all('/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches);
  606.     $j = 0;
  607.     for ($i=0; $i<count($matches[0]); $i++) {
  608.         $links_summary = (!$j) ? "\n" : $links_summary;
  609.         $j++;
  610.         $link_match = $matches[0][$i];
  611.         $link_number = '['.($i+1).']';
  612.         $link_url = $matches[2][$i];
  613.         $link_text = $matches[4][$i];
  614.         $content = str_replace($link_match, $link_text.' '.$link_number, $content);
  615.         $link_url = (strtolower(substr($link_url,0,7)) != 'http://') ? get_settings('home') . $link_url : $link_url;
  616.         $links_summary .= "\n".$link_number.' '.$link_url;
  617.     }
  618.     $content = strip_tags($content);
  619.     $content .= $links_summary;
  620.     return $content;
  621. }
  622.  
  623.  
  624. function xmlrpc_getposttitle($content) {
  625.     global $post_default_title;
  626.     if (preg_match('/<title>(.+?)<\/title>/is', $content, $matchtitle)) {
  627.         $post_title = $matchtitle[0];
  628.         $post_title = preg_replace('/<title>/si', '', $post_title);
  629.         $post_title = preg_replace('/<\/title>/si', '', $post_title);
  630.     } else {
  631.         $post_title = $post_default_title;
  632.     }
  633.     return $post_title;
  634. }
  635.     
  636. function xmlrpc_getpostcategory($content) {
  637.     global $post_default_category;
  638.     if (preg_match('/<category>(.+?)<\/category>/is', $content, $matchcat)) {
  639.         $post_category = $matchcat[0];
  640.         $post_category = preg_replace('/<category>/si', '', $post_category);
  641.         $post_category = preg_replace('/<\/category>/si', '', $post_category);
  642.  
  643.     } else {
  644.         $post_category = $post_default_category;
  645.     }
  646.     return $post_category;
  647. }
  648.  
  649. function xmlrpc_removepostdata($content) {
  650.     $content = preg_replace('/<title>(.+?)<\/title>/si', '', $content);
  651.     $content = preg_replace('/<category>(.+?)<\/category>/si', '', $content);
  652.     $content = trim($content);
  653.     return $content;
  654. }
  655.  
  656. function debug_fopen($filename, $mode) {
  657.     global $debug;
  658.     if ($debug == 1) {
  659.         $fp = fopen($filename, $mode);
  660.         return $fp;
  661.     } else {
  662.         return false;
  663.     }
  664. }
  665.  
  666. function debug_fwrite($fp, $string) {
  667.     global $debug;
  668.     if ($debug == 1) {
  669.         fwrite($fp, $string);
  670.     }
  671. }
  672.  
  673. function debug_fclose($fp) {
  674.     global $debug;
  675.     if ($debug == 1) {
  676.         fclose($fp);
  677.     }
  678. }
  679.  
  680. function pingback($content, $post_ID) {
  681. include_once (ABSPATH . WPINC . '/class-xmlrpc.php');
  682. include_once (ABSPATH . WPINC . '/class-xmlrpcs.php');
  683.     // original code by Mort (http://mort.mine.nu:8080)
  684.     global $wp_version;
  685.     $log = debug_fopen('./pingback.log', 'a');
  686.     $post_links = array();
  687.     debug_fwrite($log, 'BEGIN '.time()."\n");
  688.  
  689.     // Variables
  690.     $ltrs = '\w';
  691.     $gunk = '/#~:.?+=&%@!\-';
  692.     $punc = '.:?\-';
  693.     $any = $ltrs.$gunk.$punc;
  694.     $pingback_str_dquote = 'rel="pingback"';
  695.     $pingback_str_squote = 'rel=\'pingback\'';
  696.     $x_pingback_str = 'x-pingback: ';
  697.     $pingback_href_original_pos = 27;
  698.  
  699.     // Step 1
  700.     // Parsing the post, external links (if any) are stored in the $post_links array
  701.     // This regexp comes straight from phpfreaks.com
  702.     // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
  703.     preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
  704.  
  705.     // Debug
  706.     debug_fwrite($log, 'Post contents:');
  707.     debug_fwrite($log, $content."\n");
  708.     
  709.     // Step 2.
  710.     // Walking thru the links array
  711.     // first we get rid of links pointing to sites, not to specific files
  712.     // Example:
  713.     // http://dummy-weblog.org
  714.     // http://dummy-weblog.org/
  715.     // http://dummy-weblog.org/post.php
  716.     // We don't wanna ping first and second types, even if they have a valid <link/>
  717.  
  718.     foreach($post_links_temp[0] as $link_test){
  719.         $test = parse_url($link_test);
  720.         if (isset($test['query'])) {
  721.             $post_links[] = $link_test;
  722.         } elseif(($test['path'] != '/') && ($test['path'] != '')) {
  723.             $post_links[] = $link_test;
  724.         }
  725.     }
  726.  
  727.     foreach ($post_links as $pagelinkedto){
  728.         debug_fwrite($log, 'Processing -- '.$pagelinkedto."\n\n");
  729.  
  730.         $bits = parse_url($pagelinkedto);
  731.         if (!isset($bits['host'])) {
  732.             debug_fwrite($log, 'Couldn\'t find a hostname for '.$pagelinkedto."\n\n");
  733.             continue;
  734.         }
  735.         $host = $bits['host'];
  736.         $path = isset($bits['path']) ? $bits['path'] : '';
  737.         if (isset($bits['query'])) {
  738.             $path .= '?'.$bits['query'];
  739.         }
  740.         if (!$path) {
  741.             $path = '/';
  742.         }
  743.         $port = isset($bits['port']) ? $bits['port'] : 80;
  744.  
  745.         // Try to connect to the server at $host
  746.         $fp = fsockopen($host, $port, $errno, $errstr, 30);
  747.         if (!$fp) {
  748.             debug_fwrite($log, 'Couldn\'t open a connection to '.$host."\n\n");
  749.             continue;
  750.         }
  751.  
  752.         // Send the GET request
  753.         $request = "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: WordPress/$wp_version PHP/" . phpversion() . "\r\n\r\n";
  754.         ob_end_flush();
  755.         fputs($fp, $request);
  756.  
  757.         // Start receiving headers and content
  758.         $contents = '';
  759.         $headers = '';
  760.         $gettingHeaders = true;
  761.         $found_pingback_server = 0;
  762.         while (!feof($fp)) {
  763.             $line = fgets($fp, 4096);
  764.             if (trim($line) == '') {
  765.                 $gettingHeaders = false;
  766.             }
  767.             if (!$gettingHeaders) {
  768.                 $contents .= trim($line)."\n";
  769.                 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
  770.                 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
  771.             } else {
  772.                 $headers .= trim($line)."\n";
  773.                 $x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str);
  774.             }
  775.             if ($x_pingback_header_offset) {
  776.                 preg_match('#x-pingback: (.+)#is', $headers, $matches);
  777.                 $pingback_server_url = trim($matches[1]);
  778.                 debug_fwrite($log, "Pingback server found from X-Pingback header @ $pingback_server_url\n");
  779.                 $found_pingback_server = 1;
  780.                 break;
  781.             }
  782.             if ($pingback_link_offset_dquote || $pingback_link_offset_squote) {
  783.                 $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
  784.                 $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
  785.                 $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
  786.                 $pingback_href_start = $pingback_href_pos+6;
  787.                 $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
  788.                 $pingback_server_url_len = $pingback_href_end-$pingback_href_start;
  789.                 $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
  790.                 debug_fwrite($log, "Pingback server found from Pingback <link /> tag @ $pingback_server_url\n");
  791.                 $found_pingback_server = 1;
  792.                 break;
  793.             }
  794.         }
  795.  
  796.         if (!$found_pingback_server) {
  797.             debug_fwrite($log, "Pingback server not found\n\n*************************\n\n");
  798.             @fclose($fp);
  799.         } else {
  800.             debug_fwrite($log,"\n\nPingback server data\n");
  801.  
  802.             // Assuming there's a "http://" bit, let's get rid of it
  803.             $host_clear = substr($pingback_server_url, 7);
  804.  
  805.             //  the trailing slash marks the end of the server name
  806.             $host_end = strpos($host_clear, '/');
  807.  
  808.             // Another clear cut
  809.             $host_len = $host_end-$host_start;
  810.             $host = substr($host_clear, 0, $host_len);
  811.             debug_fwrite($log, 'host: '.$host."\n");
  812.  
  813.             // If we got the server name right, the rest of the string is the server path
  814.             $path = substr($host_clear,$host_end);
  815.             debug_fwrite($log, 'path: '.$path."\n\n");
  816.  
  817.              // Now, the RPC call
  818.             $method = 'pingback.ping';
  819.             debug_fwrite($log, 'Page Linked To: '.$pagelinkedto."\n");
  820.             debug_fwrite($log, 'Page Linked From: ');
  821.             $pagelinkedfrom = get_permalink($post_ID);
  822.             debug_fwrite($log, $pagelinkedfrom."\n");
  823.  
  824.             $client = new xmlrpc_client($path, $host, 80);
  825.             $message = new xmlrpcmsg($method, array(new xmlrpcval($pagelinkedfrom), new xmlrpcval($pagelinkedto)));
  826.             $result = $client->send($message);
  827.             if ($result){
  828.                 if (!$result->value()){
  829.                     debug_fwrite($log, $result->faultCode().' -- '.$result->faultString());
  830.                 } else {
  831.                     $value = phpxmlrpc_decode($result->value());
  832.                     if (is_array($value)) {
  833.                         $value_arr = '';
  834.                         foreach($value as $blah) {
  835.                             $value_arr .= $blah.' |||| ';
  836.                         }
  837.                         debug_fwrite($log, $value_arr);
  838.                     } else {
  839.                         debug_fwrite($log, $value);
  840.                     }
  841.                 }
  842.             }
  843.             @fclose($fp);
  844.         }
  845.     }
  846.  
  847.     debug_fwrite($log, "\nEND: ".time()."\n****************************\n\r");
  848.     debug_fclose($log);
  849. }
  850.  
  851. function doGeoUrlHeader($post_list = '') {
  852.     global $posts;
  853.  
  854.     if ($posts && 1 === count($posts) && ! empty($posts[0]->post_lat)) {
  855.         // there's only one result  see if it has a geo code
  856.         $row = $posts[0];
  857.         $lat = $row->post_lat;
  858.         $lon = $row->post_lon;
  859.         $title = $row->post_title;
  860.         if(($lon != null) && ($lat != null) ) {
  861.             echo "<meta name=\"ICBM\" content=\"".$lat.", ".$lon."\" />\n";
  862.             echo "<meta name=\"DC.title\" content=\"".convert_chars(strip_tags(get_bloginfo("name")))." - ".$title."\" />\n";
  863.             echo "<meta name=\"geo.position\" content=\"".$lat.";".$lon."\" />\n";
  864.             return;
  865.         }
  866.     } else {
  867.         if(get_settings('use_default_geourl')) {
  868.             // send the default here 
  869.             echo "<meta name='ICBM' content=\"". get_settings('default_geourl_lat') .", ". get_settings('default_geourl_lon') ."\" />\n";
  870.             echo "<meta name='DC.title' content=\"".convert_chars(strip_tags(get_bloginfo("name")))."\" />\n";
  871.             echo "<meta name='geo.position' content=\"". get_settings('default_geourl_lat') .";". get_settings('default_geourl_lon') ."\" />\n";
  872.         }
  873.     }
  874. }
  875.  
  876. function getRemoteFile($host,$path) {
  877.     $fp = fsockopen($host, 80, $errno, $errstr);
  878.     if ($fp) {
  879.         fputs($fp,"GET $path HTTP/1.0\r\nHost: $host\r\n\r\n");
  880.         while ($line = fgets($fp, 4096)) {
  881.             $lines[] = $line;
  882.         }
  883.         fclose($fp);
  884.         return $lines;
  885.     } else {
  886.         return false;
  887.     }
  888. }
  889.  
  890. function pingGeoURL($blog_ID) {
  891.  
  892.     $ourUrl = get_settings('home') ."/index.php?p=".$blog_ID;
  893.     $host="geourl.org";
  894.     $path="/ping/?p=".$ourUrl;
  895.     getRemoteFile($host,$path); 
  896. }
  897.  
  898. /* wp_set_comment_status:
  899.    part of otaku42's comment moderation hack
  900.    changes the status of a comment according to $comment_status.
  901.    allowed values:
  902.    hold   : set comment_approve field to 0
  903.    approve: set comment_approve field to 1
  904.    delete : remove comment out of database
  905.    
  906.    returns true if change could be applied
  907.    returns false on database error or invalid value for $comment_status
  908.  */
  909. function wp_set_comment_status($comment_id, $comment_status) {
  910.     global $wpdb, $tablecomments;
  911.  
  912.     switch($comment_status) {
  913.         case 'hold':
  914.             $query = "UPDATE $tablecomments SET comment_approved='0' WHERE comment_ID='$comment_id' LIMIT 1";
  915.         break;
  916.         case 'approve':
  917.             $query = "UPDATE $tablecomments SET comment_approved='1' WHERE comment_ID='$comment_id' LIMIT 1";
  918.         break;
  919.         case 'delete':
  920.             $query = "DELETE FROM $tablecomments WHERE comment_ID='$comment_id' LIMIT 1";
  921.         break;
  922.         default:
  923.             return false;
  924.     }
  925.     
  926.     if ($wpdb->query($query)) {
  927.         return true;
  928.     } else {
  929.         return false;
  930.     }
  931. }
  932.  
  933.  
  934. /* wp_get_comment_status
  935.    part of otaku42's comment moderation hack
  936.    gets the current status of a comment
  937.  
  938.    returned values:
  939.    "approved"  : comment has been approved
  940.    "unapproved": comment has not been approved
  941.    "deleted   ": comment not found in database
  942.  
  943.    a (boolean) false signals an error
  944.  */
  945. function wp_get_comment_status($comment_id) {
  946.     global $wpdb, $tablecomments;
  947.     
  948.     $result = $wpdb->get_var("SELECT comment_approved FROM $tablecomments WHERE comment_ID='$comment_id' LIMIT 1");
  949.     if ($result == NULL) {
  950.         return "deleted";
  951.     } else if ($result == "1") {
  952.         return "approved";
  953.     } else if ($result == "0") {
  954.         return "unapproved";
  955.     } else {
  956.         return false;
  957.     }
  958. }
  959.  
  960. function wp_notify_postauthor($comment_id, $comment_type='comment') {
  961.     global $wpdb, $tablecomments, $tableposts, $tableusers;
  962.     global $querystring_start, $querystring_equal, $querystring_separator;
  963.     
  964.     $comment = $wpdb->get_row("SELECT * FROM $tablecomments WHERE comment_ID='$comment_id' LIMIT 1");
  965.     $post = $wpdb->get_row("SELECT * FROM $tableposts WHERE ID='$comment->comment_post_ID' LIMIT 1");
  966.     $user = $wpdb->get_row("SELECT * FROM $tableusers WHERE ID='$post->post_author' LIMIT 1");
  967.  
  968.     if ('' == $user->user_email) return false; // If there's no email to send the comment to
  969.  
  970.     $comment_author_domain = gethostbyaddr($comment->comment_author_IP);
  971.  
  972.     $blogname = stripslashes(get_settings('blogname'));
  973.     
  974.     if ('comment' == $comment_type) {
  975.         $notify_message  = "New comment on your post #$comment->comment_post_ID \"".stripslashes($post->post_title)."\"\r\n\r\n";
  976.         $notify_message .= "Author : $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
  977.         $notify_message .= "E-mail : $comment->comment_author_email\r\n";
  978.         $notify_message .= "URI    : $comment->comment_author_url\r\n";
  979.         $notify_message .= "Whois  : http://ws.arin.net/cgi-bin/whois.pl?queryinput=$comment->comment_author_IP\r\n";
  980.         $notify_message .= "Comment:\r\n".stripslashes($comment->comment_content)."\r\n\r\n";
  981.         $notify_message .= "You can see all comments on this post here: \r\n";
  982.         $subject = '[' . $blogname . '] Comment: "' .stripslashes($post->post_title).'"';
  983.     } elseif ('trackback' == $comment_type) {
  984.         $notify_message  = "New trackback on your post #$comment_post_ID \"".stripslashes($post->post_title)."\"\r\n\r\n";
  985.         $notify_message .= "Website: $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
  986.         $notify_message .= "URI    : $comment->comment_author_url\r\n";
  987.         $notify_message .= "Excerpt: \n".stripslashes($comment->comment_content)."\r\n\r\n";
  988.         $notify_message .= "You can see all trackbacks on this post here: \r\n";
  989.         $subject = '[' . $blogname . '] Trackback: "' .stripslashes($post->post_title).'"';
  990.     } elseif ('pingback' == $comment_type) {
  991.         $notify_message  = "New pingback on your post #$comment_post_ID \"".stripslashes($post->post_title)."\"\r\n\r\n";
  992.         $notify_message .= "Website: $comment->comment_author\r\n";
  993.         $notify_message .= "URI    : $comment->comment_author_url\r\n";
  994.         $notify_message .= "Excerpt: \n[...] $original_context [...]\r\n\r\n";
  995.         $notify_message .= "You can see all pingbacks on this post here: \r\n";
  996.         $subject = '[' . $blogname . '] Pingback: "' .stripslashes($post->post_title).'"';
  997.     }
  998.     $notify_message .= get_permalink($comment->comment_post_ID) . '#comments';
  999.  
  1000.     if ('' == $comment->comment_author_email || '' == $comment->comment_author) {
  1001.         $from = "From: \"$blogname\" <wordpress@" . $_SERVER['SERVER_NAME'] . '>';
  1002.     } else {
  1003.         $from = 'From: "' . stripslashes($comment->comment_author) . "\" <$comment->comment_author_email>";
  1004.     }
  1005.  
  1006.     $message_headers = "MIME-Version: 1.0\r\n"
  1007.         . "$from\r\n"
  1008.         . "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\r\n";
  1009.  
  1010.     @mail($user->user_email, $subject, $notify_message, $message_headers);
  1011.    
  1012.     return true;
  1013. }
  1014.  
  1015. /* wp_notify_moderator
  1016.    notifies the moderator of the blog (usually the admin)
  1017.    about a new comment that waits for approval
  1018.    always returns true
  1019.  */
  1020. function wp_notify_moderator($comment_id) {
  1021.     global $wpdb, $tablecomments, $tableposts, $tableusers;
  1022.     global $querystring_start, $querystring_equal, $querystring_separator;
  1023.     
  1024.     $comment = $wpdb->get_row("SELECT * FROM $tablecomments WHERE comment_ID='$comment_id' LIMIT 1");
  1025.     $post = $wpdb->get_row("SELECT * FROM $tableposts WHERE ID='$comment->comment_post_ID' LIMIT 1");
  1026.     $user = $wpdb->get_row("SELECT * FROM $tableusers WHERE ID='$post->post_author' LIMIT 1");
  1027.  
  1028.     $comment_author_domain = gethostbyaddr($comment->comment_author_IP);
  1029.     $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $tablecomments WHERE comment_approved = '0'");
  1030.  
  1031.     $notify_message  = "A new comment on the post #$comment->comment_post_ID \"".stripslashes($post->post_title)."\" is waiting for your approval\r\n\r\n";
  1032.     $notify_message .= "Author : $comment->comment_author (IP: $comment->comment_author_IP , $comment_author_domain)\r\n";
  1033.     $notify_message .= "E-mail : $comment->comment_author_email\r\n";
  1034.     $notify_message .= "URL    : $comment->comment_author_url\r\n";
  1035.     $notify_message .= "Whois  : http://ws.arin.net/cgi-bin/whois.pl?queryinput=$comment->comment_author_IP\r\n";
  1036.     $notify_message .= "Comment:\r\n".stripslashes($comment->comment_content)."\r\n\r\n";
  1037.     $notify_message .= "To approve this comment, visit: " . get_settings('siteurl') . "/wp-admin/post.php?action=mailapprovecomment&p=".$comment->comment_post_ID."&comment=$comment_id\r\n";
  1038.     $notify_message .= "To delete this comment, visit: " . get_settings('siteurl') . "/wp-admin/post.php?action=confirmdeletecomment&p=".$comment->comment_post_ID."&comment=$comment_id\r\n";
  1039.     $notify_message .= "Currently $comments_waiting comments are waiting for approval. Please visit the moderation panel:\r\n";
  1040.     $notify_message .= get_settings('siteurl') . "/wp-admin/moderation.php\r\n";
  1041.  
  1042.     $subject = '[' . stripslashes(get_settings('blogname')) . '] Please approve: "' .stripslashes($post->post_title).'"';
  1043.     $admin_email = get_settings("admin_email");
  1044.     $from  = "From: $admin_email";
  1045.  
  1046.     $message_headers = "MIME-Version: 1.0\r\n"
  1047.         . "$from\r\n"
  1048.         . "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\r\n";
  1049.  
  1050.     @mail($admin_email, $subject, $notify_message, $message_headers);
  1051.     
  1052.     return true;
  1053. }
  1054.  
  1055.  
  1056. function start_wp() {
  1057.     global $post, $id, $postdata, $authordata, $day, $preview, $page, $pages, $multipage, $more, $numpages;
  1058.     global $pagenow;
  1059.     if (!$preview) {
  1060.         $id = $post->ID;
  1061.     } else {
  1062.         $id = 0;
  1063.         $postdata = array (
  1064.             'ID' => 0,
  1065.             'Author_ID' => $_GET['preview_userid'],
  1066.             'Date' => $_GET['preview_date'],
  1067.             'Content' => $_GET['preview_content'],
  1068.             'Excerpt' => $_GET['preview_excerpt'],
  1069.             'Title' => $_GET['preview_title'],
  1070.             'Category' => $_GET['preview_category'],
  1071.             'Notify' => 1
  1072.             );
  1073.     }
  1074.     $authordata = get_userdata($post->post_author);
  1075.  
  1076.     $day = mysql2date('d.m.y', $post->post_date);
  1077.     $currentmonth = mysql2date('m', $post->post_date);
  1078.     $numpages = 1;
  1079.     if (!$page)
  1080.         $page = 1;
  1081.     if (isset($p))
  1082.         $more = 1;
  1083.     $content = $post->post_content;
  1084.     if (preg_match('/<!--nextpage-->/', $post->post_content)) {
  1085.         if ($page > 1)
  1086.             $more = 1;
  1087.         $multipage = 1;
  1088.         $content = stripslashes($post->post_content);
  1089.         $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
  1090.         $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
  1091.         $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
  1092.         $pages = explode('<!--nextpage-->', $content);
  1093.         $numpages = count($pages);
  1094.     } else {
  1095.         $pages[0] = stripslashes($post->post_content);
  1096.         $multipage = 0;
  1097.     }
  1098.     return true;
  1099. }
  1100.  
  1101. function is_new_day() {
  1102.     global $day, $previousday;
  1103.     if ($day != $previousday) {
  1104.         return(1);
  1105.     } else {
  1106.         return(0);
  1107.     }
  1108. }
  1109.  
  1110. // Filters: these are the core of WP's plugin architecture
  1111.  
  1112. function apply_filters($tag, $string) {
  1113.     global $wp_filter;
  1114.     if (isset($wp_filter['all'])) {
  1115.         foreach ($wp_filter['all'] as $priority => $functions) {
  1116.             if (isset($wp_filter[$tag][$priority]))
  1117.                 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
  1118.             else
  1119.                 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
  1120.             $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
  1121.         }
  1122.  
  1123.     }
  1124.     
  1125.     if (isset($wp_filter[$tag])) {
  1126.         ksort($wp_filter[$tag]);
  1127.         foreach ($wp_filter[$tag] as $priority => $functions) {
  1128.             foreach($functions as $function) {
  1129.                     $string = $function($string);
  1130.             }
  1131.         }
  1132.     }
  1133.     return $string;
  1134. }
  1135.  
  1136. function add_filter($tag, $function_to_add, $priority = 10) {
  1137.     global $wp_filter;
  1138.     // So the format is wp_filter['tag']['array of priorities']['array of functions']
  1139.     if (!@in_array($function_to_add, $wp_filter[$tag]["$priority"])) {
  1140.         $wp_filter[$tag]["$priority"][] = $function_to_add;
  1141.     }
  1142.     return true;
  1143. }
  1144.  
  1145. function remove_filter($tag, $function_to_remove, $priority = 10) {
  1146.     global $wp_filter;
  1147.     if (@in_array($function_to_remove, $wp_filter[$tag]["$priority"])) {
  1148.         foreach ($wp_filter[$tag]["$priority"] as $function) {
  1149.             if ($function_to_remove != $function) {
  1150.                 $new_function_list[] = $function;
  1151.             }
  1152.         }
  1153.         $wp_filter[$tag]["$priority"] = $new_function_list;
  1154.     }
  1155.     //die(var_dump($wp_filter));
  1156.     return true;
  1157. }
  1158.  
  1159. // The *_action functions are just aliases for the *_filter functions, they take special strings instead of generic content
  1160.  
  1161. function do_action($tag, $string) {
  1162.     return apply_filters($tag, $string);
  1163. }
  1164.  
  1165. function add_action($tag, $function_to_add, $priority = 10) {
  1166.     add_filter($tag, $function_to_add, $priority);
  1167. }
  1168.  
  1169. function remove_action($tag, $function_to_remove, $priority = 10) {
  1170.     remove_filter($tag, $function_to_remove, $priority);
  1171. }
  1172.  
  1173. /* rewrite_rules
  1174.  * Construct rewrite matches and queries from permalink structure.
  1175.  * matches - The name of the match array to use in the query strings.
  1176.  *           If empty, $1, $2, $3, etc. are used.
  1177.  * Returns an associate array of matches and queries.
  1178.  */
  1179. function rewrite_rules($matches = '', $permalink_structure = '') {
  1180.  
  1181.     function preg_index($number, $matches = '') {
  1182.         $match_prefix = '$';
  1183.         $match_suffix = '';
  1184.         
  1185.         if (! empty($matches)) {
  1186.             $match_prefix = '$' . $matches . '['; 
  1187.                                                $match_suffix = ']';
  1188.         }        
  1189.         
  1190.         return "$match_prefix$number$match_suffix";        
  1191.     }
  1192.     
  1193.     $rewrite = array();
  1194.  
  1195.     if (empty($permalink_structure)) {
  1196.         $permalink_structure = get_settings('permalink_structure');
  1197.         
  1198.         if (empty($permalink_structure)) {
  1199.             return $rewrite;
  1200.         }
  1201.     }
  1202.  
  1203.     $rewritecode = 
  1204.     array(
  1205.     '%year%',
  1206.     '%monthnum%',
  1207.     '%day%',
  1208.     '%hour%',
  1209.     '%minute%',
  1210.     '%second%',
  1211.     '%postname%',
  1212.     '%post_id%'
  1213.     );
  1214.  
  1215.     $rewritereplace = 
  1216.     array(
  1217.     '([0-9]{4})?',
  1218.     '([0-9]{1,2})?',
  1219.     '([0-9]{1,2})?',
  1220.     '([0-9]{1,2})?',
  1221.     '([0-9]{1,2})?',
  1222.     '([0-9]{1,2})?',
  1223.     '([_0-9a-z-]+)?',
  1224.     '([0-9]+)?'
  1225.     );
  1226.  
  1227.     $queryreplace = 
  1228.     array (
  1229.     'year=',
  1230.     'monthnum=',
  1231.     'day=',
  1232.     'hour=',
  1233.     'minute=',
  1234.     'second=',
  1235.     'name=',
  1236.     'p='
  1237.     );
  1238.  
  1239.  
  1240.     $match = str_replace('/', '/?', $permalink_structure);
  1241.     $match = preg_replace('|/[?]|', '', $match, 1);
  1242.  
  1243.     $match = str_replace($rewritecode, $rewritereplace, $match);
  1244.     $match = preg_replace('|[?]|', '', $match, 1);
  1245.  
  1246.     $feedmatch = trailingslashit(str_replace('?/?', '/', $match));
  1247.     $trackbackmatch = $feedmatch;
  1248.  
  1249.     preg_match_all('/%.+?%/', $permalink_structure, $tokens);
  1250.  
  1251.     $query = 'index.php?';
  1252.     $feedquery = 'wp-feed.php?';
  1253.     $trackbackquery = 'wp-trackback.php?';
  1254.     for ($i = 0; $i < count($tokens[0]); ++$i) {
  1255.              if (0 < $i) {
  1256.                  $query .= '&';
  1257.                  $feedquery .= '&';
  1258.                  $trackbackquery .= '&';
  1259.              }
  1260.              
  1261.              $query_token = str_replace($rewritecode, $queryreplace, $tokens[0][$i]) . preg_index($i+1, $matches);
  1262.              $query .= $query_token;
  1263.              $feedquery .= $query_token;
  1264.              $trackbackquery .= $query_token;
  1265.              }
  1266.     ++$i;
  1267.  
  1268.     // Add post paged stuff
  1269.     $match .= '([0-9]+)?/?$';
  1270.     $query .= '&page=' . preg_index($i, $matches);
  1271.  
  1272.     // Add post feed stuff
  1273.     $feedregex = '(feed|rdf|rss|rss2|atom)/?$';
  1274.     $feedmatch .= $feedregex;
  1275.     $feedquery .= '&feed=' . preg_index($i, $matches);
  1276.  
  1277.     // Add post trackback stuff
  1278.     $trackbackregex = 'trackback/?$';
  1279.     $trackbackmatch .= $trackbackregex;
  1280.  
  1281.     // Site feed
  1282.     $sitefeedmatch = 'feed/?([_0-9a-z-]+)?/?$';
  1283.     $sitefeedquery = 'wp-feed.php?feed=' . preg_index(1, $matches);
  1284.  
  1285.     // Site comment feed
  1286.     $sitecommentfeedmatch = 'comments/feed/?([_0-9a-z-]+)?/?$';
  1287.     $sitecommentfeedquery = 'wp-feed.php?feed=' . preg_index(1, $matches) . '&withcomments=1';
  1288.  
  1289.     // Code for nice categories and authors, currently not very flexible
  1290.     $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
  1291.     if ( '' == get_settings('category_base') )
  1292.         $catmatch = $front . 'category/';
  1293.     else
  1294.         $catmatch = get_settings('category_base') . '/';
  1295.     $catmatch = preg_replace('|^/+|', '', $catmatch);
  1296.     
  1297.     $catfeedmatch = $catmatch . '(.*)/' . $feedregex;
  1298.     $catfeedquery = 'wp-feed.php?category_name=' . preg_index(1, $matches) . '&feed=' . preg_index(2, $matches);
  1299.  
  1300.     $catmatch = $catmatch . '?(.*)';
  1301.     $catquery = 'index.php?category_name=' . preg_index(1, $matches);
  1302.  
  1303.     $authormatch = $front . 'author/';
  1304.     $authormatch = preg_replace('|^/+|', '', $authormatch);
  1305.  
  1306.     $authorfeedmatch = $authormatch . '(.*)/' . $feedregex;
  1307.     $authorfeedquery = 'wp-feed.php?author_name=' . preg_index(1, $matches) . '&feed=' . preg_index(2, $matches);
  1308.  
  1309.     $authormatch = $authormatch . '?(.*)';
  1310.     $authorquery = 'index.php?author_name=' . preg_index(1, $matches);
  1311.  
  1312.     $rewrite = array(
  1313.                      $catfeedmatch => $catfeedquery,
  1314.                      $catmatch => $catquery,
  1315.                      $authorfeedmatch => $authorfeedquery,
  1316.                      $authormatch => $authorquery,
  1317.                      $match => $query,
  1318.                      $feedmatch => $feedquery,
  1319.                      $trackbackmatch => $trackbackquery,
  1320.                      $sitefeedmatch => $sitefeedquery,
  1321.                      $sitecommentfeedmatch => $sitecommentfeedquery
  1322.                      );
  1323.  
  1324.     return $rewrite;
  1325. }
  1326.  
  1327. function get_posts($args) {
  1328.     global $wpdb, $tableposts;
  1329.     parse_str($args, $r);
  1330.     if (!isset($r['numberposts'])) $r['numberposts'] = 5;
  1331.     if (!isset($r['offset'])) $r['offset'] = 0;
  1332.     // The following not implemented yet
  1333.     if (!isset($r['category'])) $r['category'] = '';
  1334.     if (!isset($r['orderby'])) $r['orderby'] = '';
  1335.     if (!isset($r['order'])) $r['order'] = '';
  1336.  
  1337.     $now = current_time('mysql');
  1338.  
  1339.     $posts = $wpdb->get_results("SELECT DISTINCT * FROM $tableposts WHERE post_date <= '$now' AND (post_status = 'publish') GROUP BY $tableposts.ID ORDER BY post_date DESC LIMIT " . $r['offset'] . ',' . $r['numberposts']);
  1340.     
  1341.     return $posts;
  1342. }
  1343.  
  1344. function check_comment($author, $email, $url, $comment, $user_ip) {
  1345.     if (1 == get_settings('comment_moderation')) return false; // If moderation is set to manual
  1346.  
  1347.     if ( (count(explode('http:', $comment)) - 1) >= get_settings('comment_max_links') )
  1348.         return false; // Check # of external links
  1349.  
  1350.     if ('' == trim( get_settings('moderation_keys') ) ) return true; // If moderation keys are empty
  1351.     $words = explode("\n", get_settings('moderation_keys') );
  1352.     foreach ($words as $word) {
  1353.     $word = trim($word);
  1354.     $pattern = "#$word#i";
  1355.         if ( preg_match($pattern, $author) ) return false;
  1356.         if ( preg_match($pattern, $email) ) return false;
  1357.         if ( preg_match($pattern, $url) ) return false;
  1358.         if ( preg_match($pattern, $comment) ) return false;
  1359.         if ( preg_match($pattern, $user_ip) ) return false;
  1360.     }
  1361.  
  1362.     return true;
  1363. }
  1364.  
  1365. function wp_head() {
  1366.     do_action('wp_head', '');
  1367. }
  1368.  
  1369. function htmlentities2($myHTML) {
  1370.     $translation_table=get_html_translation_table (HTML_ENTITIES,ENT_QUOTES);
  1371.     $translation_table[chr(38)] = '&';
  1372.     return preg_replace("/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/","&" , strtr($myHTML, $translation_table));
  1373. }
  1374.  
  1375. function wp_mail($to, $subject, $message, $headers = '', $more = '') {
  1376.     if( $headers == '' ) {
  1377.         $headers = "MIME-Version: 1.0\n" .
  1378.             "From: " . $to . " <" . $to . ">\n" .
  1379.             "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\n";
  1380.     }
  1381.     if ( function_exists('mb_send_mail') )
  1382.         return mb_send_mail($to, $subject, $message, $headers, $more);
  1383.     else
  1384.         return mail($to, $subject, $message, $headers, $more);
  1385. }
  1386.  
  1387. function wp_login($username, $password, $already_md5 = false) {
  1388.     global $wpdb, $error, $tableusers;
  1389.  
  1390.     if ( !$username )
  1391.         return false;
  1392.  
  1393.     if ( !$password ) {
  1394.         $error = __('<strong>Error</strong>: The password field is empty.');
  1395.         return false;
  1396.     }
  1397.  
  1398.     $login = $wpdb->get_row("SELECT ID, user_login, user_pass FROM $tableusers WHERE user_login = '$username'");
  1399.  
  1400.     if (!$login) {
  1401.         $error = __('<strong>Error</strong>: Wrong login.');
  1402.         return false;
  1403.     } else {
  1404.         // If the password is already_md5, it has been double hashed.
  1405.         // Otherwise, it is plain text.
  1406.         if ( ($already_md5 && $login->user_login == $username && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
  1407.             return true;
  1408.         } else {
  1409.             $error = __('<strong>Error</strong>: Incorrect password.');
  1410.             $pwd = '';
  1411.             return false;
  1412.         }
  1413.     }
  1414. }
  1415.  
  1416. function wp_specialchars( $text, $quotes = 0 ) {
  1417.     // Like htmlspecialchars except don't double-encode HTML entities
  1418.     $text = preg_replace('/&([^#])(?![a-z12]{1,8};)/', '&$1', $text);-
  1419.     $text = str_replace('<', '<', $text);
  1420.     $text = str_replace('>', '>', $text);
  1421.     if ( $quotes ) {
  1422.         $text = str_replace('"', '"', $text);
  1423.         $text = str_replace('"', ''', $text);
  1424.     }
  1425.     return $text;
  1426. }
  1427.  
  1428. ?>